package com.acme.bankapp.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.acme.bankapp.server.BankServer;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	String response;
	Scanner scanner;
	
	void run() {
		try {
			requestSocket = new Socket("localhost", BankServer.DEFAULT_PORT);
			System.out.printf("connected to %s%n",
					requestSocket.getInetAddress().getHostAddress());
			
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			in = new ObjectInputStream(requestSocket.getInputStream());
			System.out.println("Connection successful");
			System.out.println();
			
			scanner = new Scanner(System.in);
			do {
				System.out.print("client> ");
				message = scanner.nextLine();
				
				out.writeObject(message);
				out.flush();
				try {
					response = (String) in.readObject();
					System.out.printf("server> %s%n%n", response);
				} catch (ClassNotFoundException e) {
					System.out.println("Data received in unknown format");
				}
				
			} while ( !"bye".equals(response) );
			
		} catch (UnknownHostException e) {
			System.out.println("Trying to connect to unknown host");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				in.close();
				out.close();
				scanner.close();
				requestSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		(new BankClient()).run();

	}
	
}
